from django.shortcuts import redirect


class LoginMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path

        # 不需要登录的地址
        arr = [
            "/app/login/",
            "/app/register/",
        ]

        if not any(path.startswith(p) for p in arr):
            # 未登录，跳转到登录页
            if not request.session.get("username"):
                return redirect("/app/login/")

        response = self.get_response(request)
        return response
